package utils

import (
	"bufio"
	"crypto/rand"
	"fmt"
	"math"
	"math/big"
	"os"
	"runtime"
	"sort"
	"strconv"
	"time"
)

/**
 * 四舍五入
 *
 */
func Round(f float64, n int) float64 {
	pow := math.Pow10(n)
	return math.Trunc((f+0.5/pow)*pow) / pow
}

/**
 * 生成随机数
 *
 */
func RandInt64(min, max int64) int64 {
	maxBigInt := big.NewInt(max)
	i, _ := rand.Int(rand.Reader, maxBigInt)
	if i.Int64() < min {
		RandInt64(min, max)
	}
	return i.Int64()
}

/**
 * 字符串时间格式化成时间戳
 *
 * return int
 */
func FormatTime(dateStr string) (s int64, err error) {
	timestamp, err := time.ParseInLocation("2006-01-02 15:04:05", dateStr, time.Local)
	s = timestamp.Unix()
	return
}

/**
 * 返回毫秒
 *
 * return int
 */
func CurrentTimeMillis() int64 {
	return time.Now().UnixNano() / 1000000
}

/**
 * key 排序
 * return int
 */
func SortKey(list map[int]int64) (keys []int) {
	for k := range list {
		keys = append(keys, k)
	}
	sort.Ints(keys)
	return
}

func TraceFile(str ...interface{}) {
	f, err := os.OpenFile(conf.Log.File, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	w := bufio.NewWriter(f) //创建新的 Writer 对象
	defer func() {
		w.Flush()
		f.Close()
	}()
	fmt.Fprintln(w, str)
}

func Trace(str ...interface{}) {
	if conf.Log.Debug == 1 {
		fmt.Println(str)
		if conf.Log.File != "" {
			TraceFile(str)
		}
	}
}

//重写panic
func Panic(err ...interface{}) {
	_, file, line, _ := runtime.Caller(1)
	msg := file + ":" + strconv.Itoa(line)
	fmt.Println(msg)
	_bool, er := FilePathExists(conf.Log.File)
	if er != nil {
		fmt.Println("日志文件配置有误!")
		fmt.Println(er)
	} else if _bool == true {
		TraceFile(msg)
	}
	panic(err)
}

func Int64ToInt(n1 int64) int {
	n, err := strconv.Atoi(strconv.FormatInt(n1, 10))
	if err != nil {
		fmt.Println(err)
		return 0
	}
	return n
}
